using System;

namespace AspNetForums.WebServices
{
	/// <summary>
	/// Summary description for SerializablePostAttachment.
	/// </summary>
	[Serializable]
	public class SerializablePostAttachment
	{
		public SerializablePostAttachment()
		{
			//
			// TODO: Add constructor logic here
			//
		}
	
		public Components.LinkType Type
		{
			get{return type;}
			set{type = value;}
		} private Components.LinkType type;

		public AttachmentFile[] Files
		{
			get { return files; }
			set { files = value; }
		} private AttachmentFile[] files;


		public bool CanSave
		{
			get
			{
				return ( type == Components.LinkType.Zip || type == Components.LinkType.Photo );
			}
		}

		public string Save()
		{
			return Save(AspNetForums.Components.ForumContext.Current);
		}
		
		public string Save(AspNetForums.Components.ForumContext context)
		{
			if( !CanSave ) return null;
			string localUri = GetLocalPath();
			if( localUri == null ) return null;
			if( type == Components.LinkType.Zip )
				this.SaveCompressed(context.Context.Server.MapPath(localUri));
			else
				this.SaveFile(context.Context.Server.MapPath(localUri));
			return localUri;
		}

		private string GetLocalPath()
		{
			//TODO: Use config settings.
			switch( type )
			{
				case Components.LinkType.Zip :
					return AspNetForums.Components.Globals.GetSiteUrls().GetZipFileFolder() + Guid.NewGuid().ToString() + ".zip";
				case Components.LinkType.Photo :
					return AspNetForums.Components.Globals.GetSiteUrls().GetPhotoFolder() + Guid.NewGuid().ToString() + this.Files[0].RelativePath.Replace( "\\", "" ).Replace("/", "");
			}
			return null;
		}

		

		public void SaveFile(string path)
		{
			System.IO.FileStream fs;
			foreach( AttachmentFile file in files)
			{
				using( fs = System.IO.File.Create(path) )
				{
					fs.Write(file.Contents, 0, file.Contents.Length);
					fs.Close();
				}
				return;
			}
		}

		public void SaveCompressed( string fileName )
		{
			Xceed.Zip.Licenser.LicenseKey = "ZIN20-NF649-5H2S1-BKCA";
			Xceed.Zip.ZipArchive archive = new Xceed.Zip.ZipArchive( new Xceed.FileSystem.DiskFile( fileName ) );
			archive.BeginUpdate();
			foreach (AttachmentFile file in files)
			{
				Xceed.Zip.ZippedFile zipFile = ( Xceed.Zip.ZippedFile )archive.GetFile( file.RelativePath );
				if( !zipFile.Exists )
					zipFile.Create();

				using( System.IO.Stream stream = zipFile.OpenWrite( true ) )
				{
					stream.Write( file.Contents, 0, file.Contents.Length );
				}
			}
			archive.EndUpdate();
		}
        
	}


}
